package com.hand.controller;


import com.hand.entity.student;
import com.hand.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ Description   :  hello控制器
 * @ Author        :  xiong.yilin@hand-china.com
 * @ CreateDate    :  2019/8/8 21:53
 */
@Controller //返回模型和数据。restcontroller只返回数据
@RequestMapping("/hello")
public class HelloHandler {

    @Autowired
    private StudentRepository studentRepository;

    //视图
    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("list", studentRepository.findAll());
        return modelAndView;
    }

    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable("id") long id) {
        studentRepository.deleteById(id);
        return "redirect:/hello/index";
    }

    @PostMapping("/save")
    public String save(student s) {
        studentRepository.saveOrUpdate(s);
        return "redirect:/hello/index";
    }

    @PostMapping("/update")
    public String update(student s) {
        studentRepository.saveOrUpdate(s);
        return "redirect:/hello/index";
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id") long id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("update");
        modelAndView.addObject("student", studentRepository.findById(id));
        return modelAndView;
    }
}
